package com.salmon.security.app.social.openid;

import com.salmon.security.core.validate.code.SecurityConstants;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OpenIdAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private String openIdParameter = SecurityConstants.DEFAULT_PARAMETER_NAME_OPENID;
    private String providerIdParameter = SecurityConstants.DEFAULT_PARAMETER_NAME_PROVIDERID;

    public OpenIdAuthenticationFilter(){
        super(new AntPathRequestMatcher(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_SOCIAL, "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if(!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not support: " + request.getMethod());
        }
        String openId = obtainOpenId(request);
        String providerId = obtainProviderId(request);
        if(openId == null)
            openId = "";
        if (providerId == null)
            providerId = "";
        openId = openId.trim();
        providerId = providerId.trim();
        OpenIdAuthenticationToken openIdAuthenticationToken = new OpenIdAuthenticationToken(openId, providerId);
        setDetails(request, openIdAuthenticationToken);
        return this.getAuthenticationManager().authenticate(openIdAuthenticationToken);
    }

    private void setDetails(HttpServletRequest request, OpenIdAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    private String obtainOpenId(HttpServletRequest request) {
        return request.getParameter(openIdParameter);
    }
    private String obtainProviderId(HttpServletRequest request) {
        return request.getParameter(providerIdParameter);
    }
}
